import SickbedTab from '../../components/SickbedTab';
import BatchDel from '../../components/BatchDel';
import type { TableColumnsType, RadioChangeEvent } from 'antd';
import { Input, Button, Modal, Radio, Select, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { handlebedList, handlebedListEdit, handlebedSearch, handlebedDel } from '../../api/Sickbed/sickApi.ts'
import { useDispatch, useSelector } from 'react-redux';
import type { AxiosResponse } from 'axios'
import { getBedData,getBedListDel, getBedListEdit, getBedListSearch, getBedListReset } from '../../stores/bedMassage.ts'
import '../../assets/css/SickBed/SickBedManage.css'
import Pagination from '../../components/Pagination.tsx';
import {
    CheckOutlined,
    CloseOutlined,
    DeleteOutlined,
    FormOutlined
} from '@ant-design/icons';
import { ChangeEvent, useEffect, useRef, useState } from 'react';
interface DataType {
    key: React.Key;
    bednumber: string;
    department: string;
    nurse: string;
    oxygen: number;
    heart: number;
    breath: number;
    icu: number;
    aircondition: number;
    tv: number;
}
function SickbedManage() {
    let select = useSelector(state => state.bedmassage.bedlist)
    const dispatch = useDispatch()
    console.log(select);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentItem, setCurrentItem] = useState<DataType | null>();
    const [departmenttValue, setDepartmentValue] = useState('急救科' || '')
    const [nurseValue, setNurseValue] = useState('刘倩' || '')
    const [searchValue, setSearchValue] = useState('')

    const [delId, setDelId] = useState()
    const useDelId = useRef()
    // const currentData = useRef()
    // currentData.current = currentItem
    useDelId.current = delId
    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('您正在删除床位，此操作不可逆，确定删除吗？');
    const [messageApi, contextHolder] = message.useMessage();
    const [paginationInfo, setPaginationInfo] = useState({ current: 1, pageSize: 5 });

    const handleDepartment = (value: string) => {
        console.log(`selected ${value}`);
        setDepartmentValue(value)
    };

    const handlenurse = (value: string) => {
        console.log(`selected ${value}`);
        setNurseValue(value)
    };
    const showModalEdit = (item: DataType) => {
        setCurrentItem(item);
        setIsModalOpen(true);
    };

    const setInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        setCurrentItem(e.target.value);
    }

    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e);
        if (currentItem) {
            setCurrentItem({
                ...currentItem,
                [e.target.name]: e.target.value
            });
        }
    };

    const handleEditOk = async (id: any) => {
        console.log(id);
        dispatch(getBedListEdit({
            id: id,
            department: departmenttValue,
            oxygen: currentItem?.oxygen,
            heart: currentItem?.heart,
            breath: currentItem?.breath,
            icu: currentItem?.icu,
            aircondition: currentItem?.aircondition,
            tv: currentItem?.tv,
            nurse: nurseValue,
        }))
        if (currentItem) {
            const BedListEdit = await handlebedListEdit({
                id: id,
                department: departmenttValue,
                oxygen: currentItem?.oxygen,
                heart: currentItem?.heart,
                breath: currentItem?.breath,
                icu: currentItem?.icu,
                aircondition: currentItem?.aircondition,
                tv: currentItem?.tv,
                nurse: nurseValue,
            });
            console.log(BedListEdit);
            if(BedListEdit.code===1){
                messageApi.open({
                    type: 'success',
                    content: BedListEdit.msg,
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: BedListEdit.msg,
                });
            }
        }
        setIsModalOpen(false);
    };

    const handleEditCancel = () => {
        setIsModalOpen(false);
    };

    const handleSearch = async () => {
        if (searchValue !== '') {
            const bedListSearch: AxiosResponse<any, any> = await handlebedSearch({ page: 1, size: 100, bednumber: searchValue });
            console.log(bedListSearch);
            dispatch(getBedListSearch(searchValue));
            if(bedListSearch.code===1){
                messageApi.open({
                    type: 'success',
                    content: bedListSearch.msg,
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: bedListSearch.msg,
                });
            }
        } else {
            dispatch(getBedListReset())
        }
    }

    const columns: TableColumnsType<DataType> = [
        { title: '床位编辑', dataIndex: 'bednumber' },
        { title: '所属科室', dataIndex: 'department' },
        { title: '责任护士', dataIndex: 'nurse' },
        { title: '配置氧气瓶', dataIndex: 'oxygen' },
        { title: '配置心电机', dataIndex: 'heart' },
        { title: '配置呼吸机', dataIndex: 'breath' },
        { title: '配置急救设备', dataIndex: 'icu' },
        { title: '空调地暖', dataIndex: 'aircondition' },
        { title: '电视外设', dataIndex: 'tv' },
        { title: '床位操作', dataIndex: 'btn' },
    ];

    const dataSource = select.map<DataType>((item: { id: any; bednumber: any; department: any; nurse: any; oxygen: any; heart: any; breath: any; icu: any; aircondition: any; tv: any; }) => ({
        key: item.id,
        bednumber: item.bednumber,
        department: item.department,
        nurse: item.nurse,
        oxygen: <>{item.oxygen === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        heart: <>{item.heart === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        breath: <>{item.breath === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        icu: <>{item.icu === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        aircondition: <>{item.aircondition === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        tv: <>{item.tv === 1 ? <CheckOutlined style={{ color: '#67C23A' }} /> : <CloseOutlined style={{ color: '#F56C6C' }} />}</>,
        btn: <>
            <DeleteOutlined style={{ color: '#409EFF', paddingRight: '8px' }} onClick={() => handleDel(item.id)} />
            <FormOutlined style={{ color: '#409EFF' }} onClick={() => showModalEdit(item)} />
        </>,
    }));
    console.log(dataSource);

    const handleDel = (id: any) => {
        setOpen(true);
        setDelId(id);
        setTimeout(() => {
            console.log(useDelId.current);
        }, 0);
    }

    const handleDelOk = () => {
        setConfirmLoading(true);
        setTimeout(async () => {
            dispatch(getBedListDel(useDelId.current))
            setOpen(false);
            setConfirmLoading(false);
            const bedListDel: AxiosResponse<any, any> = await handlebedDel({ id: useDelId.current })
            if(bedListDel.code===1){
                messageApi.open({
                    type: 'success',
                    content: bedListDel.msg,
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: bedListDel.msg,
                });
            }
        }, 1000);
    };

    const handleDelCancel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };

    const departmentData = [
        { value: '急救科', label: '急救科' },
        { value: '骨科', label: '骨科' },
        { value: '神经外科', label: '神经外科' },
        { value: '妇科', label: '妇科' },
        { value: '测试科室', label: '测试科室' },
        { value: '眼科', label: '眼科' },
        { value: '小儿内科', label: '小儿内科' },
        { value: '普通外科', label: '普通外科' },
        { value: '心血管内科', label: '心血管内科' },
    ]

    const nurseData = [
        { value: '刘倩', label: '刘倩' },
        { value: '7', label: '7' },
        { value: '张萍', label: '张萍' },
        { value: '张峰', label: '张峰' },
        { value: '李芳', label: '李芳' },
        { value: '孙七', label: '孙七' },
        { value: '赵六', label: '赵六' }
    ]

    const handleTableChange = (page: number, pageSize: number) => {
        setPaginationInfo({ ...paginationInfo, current: page, pageSize: pageSize });
    };

    const BedListData = async () => {
        const BedList: AxiosResponse<any, any> = await handlebedList({ page: 1, size: 100, bednumber: 1 })
        if(BedList){
            dispatch(getBedData(BedList.data))
        }
    }
    useEffect((): void => {
        const fetchData = async () => {
            await BedListData();
        };
        fetchData();
    }, [dispatch])
    return (
        <>
            <div className='sickbed-tab' style={{ width: '83vw', height: '100%', backgroundColor: 'white', borderRadius: '5px', marginLeft: '20px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '20px 30px' }}>
                    <div>
                        <span style={{ fontSize: '1vw', fontWeight: '600' }}>床位编号</span>
                        <Input placeholder="输入床位编号进行查询" value={searchValue} onChange={(e) => setSearchValue(e.target.value)} style={{ width: '17vw', margin: ' 0 3px' }} />
                        <Button type="primary" onClick={handleSearch} icon={<SearchOutlined />}>
                            查询
                        </Button>
                    </div>
                    <BatchDel selectedRowKeys={JSON.parse((localStorage as any).getItem('newSelectedRowKeys'))}></BatchDel>
                </div>
                <div style={{ width: '79vw', margin: '0 30px' }}>
                    <SickbedTab columns={columns} dataSource={dataSource} onFetchData={select} pagination={paginationInfo}></SickbedTab>
                    <Pagination listData={select} onChange={handleTableChange}></Pagination>
                </div>
            </div>
            {contextHolder}
            <Modal title="床位管理" open={isModalOpen} onOk={() => handleEditOk(currentItem?.id)} onCancel={handleEditCancel}>
                <table className='sickbed-edit'>
                    <tbody>
                        <tr className='sickbed-edit-list'>
                            <td>床位编号</td>
                            <td className='sickbed-edit-list-content'><input type='text' value={currentItem?.bednumber} onChange={setInputChange}></input></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>所属科室</td>
                            <td className='sickbed-edit-list-content'>
                                <Space wrap className='space'>
                                    <Select
                                        defaultValue="急救科"
                                        style={{ width: 120 }}
                                        onChange={handleDepartment}
                                        options={departmentData}
                                    />
                                </Space>
                            </td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>氧气罐</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='oxygen' onChange={onChange} value={currentItem?.oxygen}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>心电机</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='heart' onChange={onChange} value={currentItem?.heart}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>呼吸机</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='breath' onChange={onChange} value={currentItem?.breath}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>急救设备</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='icu' onChange={onChange} value={currentItem?.icu}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>空调地暖</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='aircondition' onChange={onChange} value={currentItem?.aircondition}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>电视外设</td>
                            <td className='sickbed-edit-list-content'>
                                <Radio.Group className='radio' name='tv' onChange={onChange} value={currentItem?.tv}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group></td>
                        </tr>
                        <tr className='sickbed-edit-list'>
                            <td>责任护士</td>
                            <td className='sickbed-edit-list-content'>
                                <Space wrap className='space'>
                                    <Select
                                        defaultValue="刘倩"
                                        style={{ width: 120 }}
                                        onChange={handlenurse}
                                        options={nurseData}
                                    />
                                </Space>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </Modal>
            <Modal
                title="系统提示"
                open={open}
                onOk={handleDelOk}
                confirmLoading={confirmLoading}
                onCancel={handleDelCancel}
            >
                <p>{modalText}</p>
            </Modal>
        </>
    );
}

export default SickbedManage;

